﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using OrganizedIN.BAL;
using OrganizedIN.BussinessServices;
using System.IO;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;

namespace OrganizedIN.UI.Calendar
{
    public partial class Search_Calendar : System.Web.UI.Page
    {
        DateTime dt = DateTime.Now;
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }


        private void BindData()
        {
            try
            {
                string strUserName = Session["UserID"].ToString();
                string strSummary = txtsrchbytitle.Text;
                string dtmDate = txtSearchByDate.Text;
                string strImportType = ddlImportType.SelectedValue;
                string strShare = txtsrchbygrp.Text;
                string strSort = ddlsort.SelectedValue;

                DataSet ds = new DataSet();
                ds = CalendarSearch(strUserName, strSummary, dtmDate, strImportType, strShare, strSort);
                dgSearchResult.DataSource = ds.Tables[0];
                dgSearchResult.DataBind();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    lblErrMsg.Text = "";
                }
                else
                {
                    lblErrMsg.Text = "No record(s) found.";
                }
            }
            catch (Exception ex)
            {
                lblErrMsg.Text = ex.Message;
            }
        }


        private void Download(string CalendarID)
        {
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = ".ics";
                        
            DataSet ds = GetCalendarDetails(CalendarID);

            if (CalendarID != string.Empty)
            {
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    string filename = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Path"]);

                    if (File.Exists(Path.Combine(Server.MapPath("~/CalendarUpload"), filename)))
                    {
                        StreamReader reader = new StreamReader(Path.Combine(Server.MapPath("~/CalendarUpload"), filename));
                        Stream stream = reader.BaseStream;
                        byte[] buffer = new byte[stream.Length];

                        Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename.Substring(0, filename.Length - 19) + filename.Substring(filename.Length - 4, 4)).Replace('+', ' '));
                        Response.AddHeader("Content-Length", Convert.ToString(buffer.Length));

                        stream.Read(buffer, 0, buffer.Length);
                        Response.BinaryWrite(buffer);
                        reader.Close();
                        stream.Close();

                        Response.Flush();
                        Response.End();
                    }
                }
            }

        }

        private void Delete(string CalendarID)
        {
            DataSet ds = GetCalendarDetails(CalendarID);

            if (CalendarID != string.Empty)
            {
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    string filename = Convert.ToString(ds.Tables[0].Rows[0]["Calendar_Path"]);

                    if (File.Exists(Path.Combine(Server.MapPath("~/CalendarUpload"), filename)))
                    {
                        File.Delete(Path.Combine(Server.MapPath("~/CalendarUpload"), filename));
                    }

                    SqlService objService = new SqlService();
                    objService.AddParameter("@vcrCalendarID", ssenumSqlDataTypes.ssSDT_String, 10, CalendarID);

                    objService.RunProc("usp_Calendar_Delete", "User_Calendar");

                    BindData();
                }
            }
        }

        private DataSet CalendarSearch(string strUserName, string strSummary, string dtmDate, string strImportType, string strShare, string strSort)
        {
            try
            {
                SqlService objService = new SqlService();
                objService.AddParameter("@vcrUserName", ssenumSqlDataTypes.ssSDT_String, 40, strUserName);
                objService.AddParameter("@vcrSummary", ssenumSqlDataTypes.ssSDT_String, 40, strSummary);
                objService.AddParameter("@vcrDate", ssenumSqlDataTypes.ssSDT_String, 40, dtmDate);
                objService.AddParameter("@vcrImportType", ssenumSqlDataTypes.ssSDT_String, 40, strImportType);
                objService.AddParameter("@vcrShare", ssenumSqlDataTypes.ssSDT_String, 40, strShare);
                objService.AddParameter("@vcrSort", ssenumSqlDataTypes.ssSDT_String, 40, strSort);
                return objService.RunProc("usp_Calendar_SearchResult", "User_Calendar");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void dgSearchResult_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "Action")
            {
                DropDownList ddlAction = (DropDownList)e.Item.FindControl("ddlAction");
                if (ddlAction.SelectedValue == "Download")
                {
                    Download(Convert.ToString(e.CommandArgument));
                }
                else if (ddlAction.SelectedValue == "Delete")
                {
                    Delete(Convert.ToString(e.CommandArgument));
                }
                else if (ddlAction.SelectedValue == "Update")
                {
                    Response.Redirect("Update_Calendar.aspx?CalendarID=" + Convert.ToString(e.CommandArgument));
                }
            }
        }

            
        private DataSet GetCalendarDetails(string CalendarID)
        {
            SqlService objService = new SqlService();
            objService.AddParameter("@vcrCalendarID", ssenumSqlDataTypes.ssSDT_String, 10, CalendarID);
            
            return objService.RunProc("usp_Calendar_Get", "User_Calendar");
        }

        protected void dgSearchResult_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            dgSearchResult.CurrentPageIndex = e.NewPageIndex;
            BindData();
        }        
    }
}
